import re
import time
import json
import requests

class Email:
    '10分钟邮箱收信类'

    cookies = ""
    address = ""

    # 初始化邮箱
    def init(self, addr):
        req = requests.post(
            "http://www.bccto.me/applymail",
            data = {"mail": addr},
            headers = {
                "Referer": "http://www.bccto.me/",
                "X-Requested-With": "XMLHttpRequest",
                "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            },
            cookies = requests.get("http://www.bccto.me/").cookies
        )

        try:
            result = json.loads(req.text);
            if result["success"] == "true":
                self.cookies = req.cookies
                self.address = result["user"]
                return True
            else:
                return False
        except ValueError:
            return False

    # 得到邮件列表
    def list(self):
        req = requests.post(
            "http://www.bccto.me/getmail",
            data = {
                "mail": self.address,
                "time": int(time.time() - 15)
            },
            headers = {
                "Referer": "http://www.bccto.me/",
                "X-Requested-With": "XMLHttpRequest",
                "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
            },
            cookies = self.cookies
        )

        try:
            result = json.loads(req.text);
            return result["mail"] if len(result["mail"])>0 else ()
        except ValueError:
            return ()

    # 得到邮件内容
    def get(self, id):
        url = "http://www.bccto.me/win/%s/%s" % (self.address.replace(".", "-_-").replace("@", "(a)"), id);
        req = requests.get(url, headers = {
            "Accept-Language": "zh-CN,zh;q=0.8,en;q=0.6"
        }, cookies = self.cookies)
        return re.findall(r'\[\]\)\.push\({}\);</script>([\s\S]+?)<script src="https://s95\.cnzz\.com/z_stat\.php', req.text)[0]

